// 云函数入口文件
const cloud = require('wx-server-sdk')
var Parser = require('rss-parser');
var md5 = require('md5');
let parser = new Parser();


cloud.init({
    env:cloud.DYNAMIC_CURRENT_ENV
})

function setImg(item) {
    let reg = /img[\s]+src=['|"]([\w|://\.-]+)/i

    let m = item.content.match(reg)

    item.img = m ? (m[1] ? m[1] : '') : '';

    return item;
}
// 云函数入口函数
exports.main = async (event, context) => {
    console.log('同步:')
    const {
        rssUrl,
        
    } = event
    console.log('同步:',rssUrl)
    let json = await parser.parseURL(rssUrl)
    const db = cloud.database({
       
    })
    let {
        items,
        link,
        title,
    } = json
 
    for (let i = 0; i < items.length; i++) {
        let id = md5(items[i].link)

        await db.collection('rss_item').doc(id).set({
            data: {
                ...setImg(items[i]),
                siteUrl:rssUrl,
                siteName:title,
                updateTime:+new Date()
            }
        })
    }
    return json
    //console.log('同步成功');
}